//
//  ZQstatusViewModel.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/17.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

import YYText
class ZQstatusViewModel: NSObject {
 //记录用户头像地址
    var iconURL : URL?

    var verifitedImage : UIImage?
    
    var mbrankImage : UIImage?
    
    //原创微博的字符串
    var originateString : NSMutableAttributedString?
    
    //转发微博的字符串
    
    var relayString : NSMutableAttributedString?
    
    //设置行高 只希望计算一次 以后就直接读取
    var rowHeight: CGFloat = 300
    
    
    //微博日期---微博来源

    var sourceText : String?
    
    //微博来源
   private func loadsourceText(source : String) -> String {
    //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">iPhone 6s 土豪金</a>
      let stear = "\">"
      let end  = "</a"
      //截取
        guard let stearRange = source.range(of: stear),let endRange = source.range(of: end)  else {
            
            return "火星手机"
        }
    //
        let range = stearRange.upperBound..<endRange.lowerBound
        
        let subtring = source.substring(with: range)
        
        return subtring
    }
    
    var status : ZQStatus? {
        
        didSet{
            
            iconURL = URL(string:status?.user?.avatar_large ?? "")
            
            dealWeiboVerifitedImage()
            dealMbrankImage()
            
            self.sourceText = loadsourceText(source: status?.source ?? "")
            
            self.originateString  = self.dealWeiBoText(str: status?.text ?? "")
            
            self.relayString = self.dealWeiBoText(str: status?.retweeted_status?.text ?? "")
        }
        
    }
    
    
    private func dealWeiBoText(str : String) -> NSMutableAttributedString {
    
        //1.实例化正则表达式 设置查找规则
        let pattern = "\\[.*?\\]"
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //2.通过原则在字符串中查找目标字符串
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
         //3遍历结果集 获re取表情字符串 (倒叙遍历)因为正序容易出错,正序每次都计算
        let strM = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        for result in results.reversed(){
            
            let range = result.rangeAt(0)
            let sub = (str as NSString) .substring(with: range)
            
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub) {
                
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil )
                
                 let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo: font, alignment: .center)
                
                 strM.replaceCharacters(in: range, with: imageText)
                
            }
            
        }
        
        //给富文本添加字体的属性
        strM.addAttributes([NSFontAttributeName : font], range: NSRange(location: 0, length: strM.length))
//        
        addHighlighted(pattern: "@\\w+", strM: strM)
        addHighlighted(pattern: "#.*?#", strM: strM)
        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM)
        return strM
        
    }
    //给特殊文版添加高亮
    private func addHighlighted(pattern:String , strM:NSMutableAttributedString){
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let str = strM.string
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //循环目标文件
        for result in results {
            
            let range = result.rangeAt(0)
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
            
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
            
            let highlight = YYTextHighlight()
            
            highlight.setColor(UIColor.orange)
            
            highlight.setBackgroundBorder(border)
            
            strM.yy_setTextHighlight(highlight, range: range)
            
            
            
            
        }
        
        
        
    }
    
    var timeText: String? {
        //1.实例化日期格式化对象
        let dateFormater = DateFormatter()
        //2.指定格式化符
        dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //在真机上必须设置本地化信息否则转换失败
        dateFormater.locale = Locale(identifier: "en")
        //3.将字符串转换日期对象
        guard let sinaDate = dateFormater.date(from: status?.created_at ?? "") else {
            return "穿越时空的少年"
        }
        //print(sinaDate)
        //4.处理日期
        //4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                } else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                } else {
                    return "\(Int(delta / 3600))小时前"
                }
            } else if calender.isDateInYesterday(sinaDate) {
                //昨天 昨天 HH:mm
                dateFormater.dateFormat = "昨天 HH:mm"
                return dateFormater.string(from: sinaDate)
            } else {
                //其他 MM-dd HH:mm
                dateFormater.dateFormat = "MM-dd HH:mm"
                return dateFormater.string(from: sinaDate)
            }
        } else {
            //非当年
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormater.string(from: sinaDate)
        }
    }
    
   
    
    //计算型属性判断应该返回什么累类型的微博
    var imageUrls : [ZQPictureInfo]? {
        
        if status?.retweeted_status == nil {
            
             //原创微博
            return status?.pic_urls
        }
        //转发微博
        return status?.retweeted_status?.pic_urls
 
    }
    
 

    //处理用户等级
   private func dealMbrankImage (){
    
    let mbImage = status?.user?.mbrank ?? 0
    if mbImage > 0 && mbImage < 7 {
        
        mbrankImage = UIImage(named: "common_icon_membership_level\(mbImage)")
        
        
     }
    
    }
    
    //处理微博认证
    
    private  func  dealWeiboVerifitedImage () {
        
    let type = status?.user?.verified_type ?? -1
        
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
           
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
            
            
        default:
            verifitedImage = nil
        }
            
            
     
       
    }
   
}
//    var timeText : String? {
//        //实例化日期
//        let dateformat = DateFormatter()
//        //指定时间格式
//        dateformat.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
//        //在真机上必须用上这句话
//        dateformat.locale = Locale(identifier: "en")
//        //将日期转换事假
//        guard let sinaDate = dateformat.date(from: status?.created_at ?? "") else{
//              return "奔跑吧骚年"
//        }
//        //处理函数
//        let calender = NSCalendar.current
//        //拿到当前日期
//        let courrent = Date()
//        //对比
//        let result = calender.dateComponents([.day,.year], from: sinaDate, to: courrent)
//
//        //判断结果是不是当年
//        if  result.year == 0{
//            //今天
//            if calender .isDateInToday(sinaDate) {
//               let data = courrent.timeIntervalSince(sinaDate)
//                if data < 60 {
//
//                return "刚刚"
//                }else if data < 60 {
//                    return "\(Int(data / 60))分钟前"
//                }else if data < 3600 {
//
//                    return "\(Int(data / 3600))小时前"
//                }
//
//            }else if calender.isDateInYesterday(sinaDate){
//            //昨天
//                dateformat.dateFormat = "HH:mm"
//
//                return dateformat.string(from: sinaDate)
//            }else{
//                dateformat.dateFormat = "MM-dd HH:mm"
//                return dateformat.string(from: sinaDate)
//
//            }
//
//        }else{
//            //非当年
//                dateformat.dateFormat = "yyyy-MM-dd HH:mm"
//                return dateformat.string(from: sinaDate)
//        }
//    }


